/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.76
        Device            :  PIC16F15356
        Driver Version    :  2.00
*/

/*
    (c) 2018 Microchip Technology Inc. and its subsidiaries. 
    
    Subject to your compliance with these terms, you may use Microchip software and any 
    derivatives exclusively with Microchip products. It is your responsibility to comply with third party 
    license terms applicable to your use of third party software (including open source software) that 
    may accompany Microchip software.
    
    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER 
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY 
    IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS 
    FOR A PARTICULAR PURPOSE.
    
    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, 
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND 
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP 
    HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO 
    THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL 
    CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT 
    OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS 
    SOFTWARE.
*/

#include "mcc_generated_files/mcc.h"
#include "mian.h"
#define SLAVE_I2C_GENERIC_RETRY_MAX     100
unsigned char Timer0IntFlag=0,Timer1IntFlag=0,Timer2IntFlag=0;
#define BL24C02
void Uart1Print(unsigned char *str)
{
    while(*str!=0)
	{
        if(EUSART1_is_tx_ready())
        {
            EUSART1_Write(*str);
        }
		str++;
	}
}
void Uart2Print(unsigned char *str)
{
    while(*str!=0)
	{
        if(EUSART2_is_tx_ready())
        {
            EUSART2_Write(*str);
        }
		str++;
	}
}
void Uart1PrintUint16(unsigned int uint16_num)
{
    if(EUSART1_is_tx_ready())
    {
        EUSART1_Write(uint16_num/10000+'0');
    }
    if(EUSART1_is_tx_ready())
    {
        EUSART1_Write(uint16_num/1000%10+'0');
    } 
    if(EUSART1_is_tx_ready())
    {
        EUSART1_Write(uint16_num%1000/100+'0');
    }      
    if(EUSART1_is_tx_ready())
    {
        EUSART1_Write(uint16_num%100/10+'0');
    } 
    if(EUSART1_is_tx_ready())
    {
        EUSART1_Write(uint16_num%10+'0');
    }          
}
void Uart2PrintUint16(unsigned int uint16_num)
{
    if(EUSART2_is_tx_ready())
    {
        EUSART2_Write(uint16_num/10000+'0');
    }
    if(EUSART2_is_tx_ready())
    {
        EUSART2_Write(uint16_num/1000%10+'0');
    } 
    if(EUSART2_is_tx_ready())
    {
        EUSART2_Write(uint16_num%1000/100+'0');
    }      
    if(EUSART2_is_tx_ready())
    {
        EUSART2_Write(uint16_num%100/10+'0');
    } 
    if(EUSART2_is_tx_ready())
    {
        EUSART2_Write(uint16_num%10+'0');
    }          
}

#define MCHP24AA512_RETRY_MAX  100  // define the retry count
#define MCHP24AA512_ADDRESS    0x50 // slave device address
#define SLAVE_I2C_GENERIC_RETRY_MAX     100
unsigned char I2C_Byte_Write(unsigned char DevAddr,unsigned char RegAddr,unsigned char Dta)
{
    unsigned char writeBuffer[2];
    writeBuffer[0]=RegAddr;
    writeBuffer[1]=Dta;
    I2C1_MESSAGE_STATUS status = I2C1_MESSAGE_PENDING;
    unsigned char timeOut = 0;
    while(status != I2C1_MESSAGE_FAIL)
    {
        // write one byte to EEPROM (3 is the number of bytes to write)
        I2C1_MasterWrite(  writeBuffer,
                                2,
                                DevAddr,
                                &status);

        // wait for the message to be sent or status has changed.
        while(status == I2C1_MESSAGE_PENDING);

        if (status == I2C1_MESSAGE_COMPLETE)
            break;

        // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
        //               or I2C1_DATA_NO_ACK,
        // The device may be busy and needs more time for the last
        // write so we can retry writing the data, this is why we
        // use a while loop here

        // check for max retry and skip this byte
        if (timeOut == SLAVE_I2C_GENERIC_RETRY_MAX)
            break;
        else
            timeOut++;
    }
}
unsigned char I2C_Page_Write(unsigned char DevAddr,unsigned char page,unsigned char DtaBuf[])
{
    I2C1_MESSAGE_STATUS status = I2C1_MESSAGE_PENDING;
    unsigned char Len=0,i,timeOut=0;
#ifdef BL24C02//2kbits 1page=8byts 
    Len=9;
    unsigned char WriteBuf[9]={0};
    WriteBuf[0]=page;
    for(i=0;i<8;i++)
        WriteBuf[i+1]=DtaBuf[i];
#else  //BL24C04 08 16 1page=16bytes
    Len=17;
    unsigned char WriteBuf[17]={0};
    WriteBuf[0]=page;
    for(i=0;i<16;i++)
        WriteBuf[i+1]=DtaBuf[i];
#endif    
    timeOut=0;
    while(status != I2C1_MESSAGE_FAIL)
    {
        // write one byte to EEPROM (3 is the number of bytes to write)
        I2C1_MasterWrite(  WriteBuf,
                                Len,
                                DevAddr,
                                &status);

        // wait for the message to be sent or status has changed.
        while(status == I2C1_MESSAGE_PENDING);

        if (status == I2C1_MESSAGE_COMPLETE)
            break;

        // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
        //               or I2C1_DATA_NO_ACK,
        // The device may be busy and needs more time for the last
        // write so we can retry writing the data, this is why we
        // use a while loop here

        // check for max retry and skip this byte
        if (timeOut == SLAVE_I2C_GENERIC_RETRY_MAX)
            break;
        else
            timeOut++;
    }
}
void delay()
{
    unsigned int i=1000;
    while(i--);

}
unsigned char I2C_Byte_Read(unsigned char DevAddr,unsigned char RegAddr,unsigned char *Dta)
{
    unsigned char writeBuffer[2];
    writeBuffer[0]=RegAddr;
    I2C1_MESSAGE_STATUS status = I2C1_MESSAGE_PENDING;
    unsigned char timeOut = 0;
    while(status != I2C1_MESSAGE_FAIL)
    {
        // write one byte to EEPROM (2 is the count of bytes to write)
        I2C1_MasterWrite(   writeBuffer,
                                1,
                                DevAddr,
                                &status);

        // wait for the message to be sent or status has changed.
        while(status == I2C1_MESSAGE_PENDING);

        if (status == I2C1_MESSAGE_COMPLETE)
            break;

        // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
        //               or I2C1_DATA_NO_ACK,
        // The device may be busy and needs more time for the last
        // write so we can retry writing the data, this is why we
        // use a while loop here

        // check for max retry and skip this byte
        if (timeOut == MCHP24AA512_RETRY_MAX)
            break;
        else
            timeOut++;
    }
    delay();//delay for bl24c02
    if (status == I2C1_MESSAGE_COMPLETE)
    {

        // this portion will read the byte from the memory location.
        timeOut = 0;
        while(status != I2C1_MESSAGE_FAIL)
        {
            // write one byte to EEPROM (2 is the count of bytes to write)
            I2C1_MasterRead(    Dta,
                                1,
                                DevAddr,
                                &status);

            // wait for the message to be sent or status has changed.
            while(status == I2C1_MESSAGE_PENDING);

            if (status == I2C1_MESSAGE_COMPLETE)
                break;

            // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
            //               or I2C1_DATA_NO_ACK,
            // The device may be busy and needs more time for the last
            // write so we can retry writing the data, this is why we
            // use a while loop here

            // check for max retry and skip this byte
            if (timeOut == MCHP24AA512_RETRY_MAX)
                break;
            else
                timeOut++;
        }
    }
}
unsigned char I2C_Bytes_Read(unsigned char DevAddr,unsigned char RegAddr,unsigned char *DtaBuf,unsigned char Len)
{
    unsigned char writeBuffer[2];
    writeBuffer[0]=RegAddr;
    I2C1_MESSAGE_STATUS status = I2C1_MESSAGE_PENDING;
    unsigned char timeOut = 0;
    while(status != I2C1_MESSAGE_FAIL)
    {
        // write one byte to EEPROM (2 is the count of bytes to write)
        I2C1_MasterWrite(   writeBuffer,
                                1,
                                DevAddr,
                                &status);

        // wait for the message to be sent or status has changed.
        while(status == I2C1_MESSAGE_PENDING);

        if (status == I2C1_MESSAGE_COMPLETE)
            break;

        // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
        //               or I2C1_DATA_NO_ACK,
        // The device may be busy and needs more time for the last
        // write so we can retry writing the data, this is why we
        // use a while loop here

        // check for max retry and skip this byte
        if (timeOut == MCHP24AA512_RETRY_MAX)
            break;
        else
            timeOut++;
    }
    delay();//delay for bl24c02
    if (status == I2C1_MESSAGE_COMPLETE)
    {

        // this portion will read the byte from the memory location.
        timeOut = 0;
        while(status != I2C1_MESSAGE_FAIL)
        {
            // write one byte to EEPROM (2 is the count of bytes to write)
            I2C1_MasterRead(    DtaBuf,
                                Len,
                                DevAddr,
                                &status);

            // wait for the message to be sent or status has changed.
            while(status == I2C1_MESSAGE_PENDING);

            if (status == I2C1_MESSAGE_COMPLETE)
                break;

            // if status is  I2C1_MESSAGE_ADDRESS_NO_ACK,
            //               or I2C1_DATA_NO_ACK,
            // The device may be busy and needs more time for the last
            // write so we can retry writing the data, this is why we
            // use a while loop here

            // check for max retry and skip this byte
            if (timeOut == MCHP24AA512_RETRY_MAX)
                break;
            else
                timeOut++;
        }
    }
}
/*
                         Main application
 */
    uint8_t read_buf[256];
    unsigned char write_buf[9];
void main(void)
{
    unsigned int timer0_cnt=0,timer1_cnt=0,timer2_cnt=0;
    uint16_t pwm3=0,pwm4=0,pwm5=0,pwm6=0;
    volatile uint8_t rxData;
    uint16_t convertedValue;    
    unsigned short i=0,j=0;
    unsigned char rand;
    // initialize the device
    SYSTEM_Initialize();
    IO_RA2_SetHigh();//power on
    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();
    //WDTCON0bits.SWDTEN=1;
    Uart1Print("Hello Pic\r\n");
    Uart2Print("Hello Pic\r\n");
    TMR0_StartTimer();
    TMR1_StartTimer();
    TMR2_StartTimer();
    while (1)
    {
        // Add your application code

        //timer0 2ms interrupt
        if(Timer0IntFlag!=0)
        {
            Timer0IntFlag=0;
            timer0_cnt++;
        }
        if(timer0_cnt>=1000/2)
        {
            timer0_cnt=0;
            convertedValue = ADC_GetConversion(channel_ANC2);            
            IO_RB5_Toggle();
            Uart1Print("adc:");
            Uart1PrintUint16(convertedValue);
            Uart1Print("\r\n");
            Uart2Print("adc:");
            Uart2PrintUint16(convertedValue);
            Uart2Print("\r\n");
            rand=(unsigned char)convertedValue;
            for(i=0;i<32;i++)//256/8
            {
                for(j=0;j<8;j++)
                write_buf[j]=rand+i;
                I2C_Page_Write(MCHP24AA512_ADDRESS,i*8,write_buf);
            }
            //I2C_Bytes_Write(MCHP24AA512_ADDRESS,write_buf,17);
            I2C_Bytes_Read(MCHP24AA512_ADDRESS,0,read_buf,256);
            Uart1Print("IIC Read:\r\n");
            for(i=0;i<256;i++)
            {
//                if(i%8==0)
//                Uart1Print("\r\n");
//                Uart1PrintUint16(read_buf[i]);
                if(read_buf[i]==rand+i/8)
                {
                
                }
                else
                {
                    Uart1PrintUint16(i);
                    Uart1Print(":addr test error!\r\n");
                    break;
                }
            }
            if(i==256)
            {
                Uart1Print("i2c eep test ok!\r\n");
            }
            else
            {
                Uart1Print("i2c eep test error!\r\n");
            }
            //BL24C02_PageWrite();
            //MCHP24AA512_Read(0,read_buf,1);
//            for(i=0;i<16;i++)
//            {
//                I2C_Byte_Write(MCHP24AA512_ADDRESS,i,i+2);
//                Uart1Print("IIC Write:");
//                Uart1PrintUint16(i+2);
//                Uart1Print("\r\n");
////                delay();
////                delay();
////                delay();
////                delay();
//                I2C_Byte_Read(MCHP24AA512_ADDRESS,i,read_buf);
//                Uart1Print("IIC Read:");
//                Uart1PrintUint16(read_buf[0]);
//                Uart1Print("\r\n");
////                delay();
////                delay();
//            }
          
            CLRWDT();
            Uart1Print("clean dog\r\n");
        }
        
        //timer1 2ms interrupt
        if(Timer1IntFlag!=0)
        {
            Timer1IntFlag=0;
            timer1_cnt++;
        }
        if(timer1_cnt>=1000/1000)
        {
            timer1_cnt=0;
            pwm3++;
            if(pwm3>0x3ff)
                pwm3=0;
            PWM3_LoadDutyValue(pwm3);
//            IO_RB4_Toggle();
//            Uart1Print("Timer1 1s\r\n");
//            Uart2Print("Timer1 1s\r\n");
        }

        //timer2 2ms interrupt
        if(Timer2IntFlag!=0)
        {
            Timer2IntFlag=0;
            timer2_cnt++;
        }
        if(timer2_cnt>=1000/250)
        {
            timer2_cnt=0;
            pwm4++;
            if(pwm4>0x3ff)
                pwm4=0;
            PWM4_LoadDutyValue(pwm4);
//            IO_RB5_Toggle();
//            Uart1Print("Timer2 1s\r\n");
//            Uart2Print("Timer2 1s\r\n");
        }  
        
        //uart
        // Logic to echo received data
        if(EUSART1_is_rx_ready())
        {
            rxData = EUSART1_Read();
            if(EUSART1_is_tx_ready())
            {
                EUSART1_Write(rxData);
            }
        }   
        // Logic to echo received data
        if(EUSART2_is_rx_ready())
        {
                rxData = EUSART2_Read();
                if(EUSART2_is_tx_ready())
                {
                    EUSART2_Write(rxData);
                }
        }
    }
}
/**
 End of File
*/